package com.crois.barrier.server.netty;

import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelOption;
import org.springframework.boot.web.embedded.netty.NettyServerCustomizer;
import reactor.netty.ReactorNetty;
import reactor.netty.http.server.HttpServer;
import reactor.netty.resources.LoopResources;

/**
 * @author Hou Ze Yu
 * @description
 * @date 2021/4/21
 */
public class BarrierNettyServerCustomizer implements NettyServerCustomizer {

    private static final int DEFAULT_IO_WORKER_COUNT = Integer.parseInt(System.getProperty(
            ReactorNetty.IO_WORKER_COUNT,
            "" + Math.max(Runtime.getRuntime()
                    .availableProcessors() << 1, 16)));


    @Override
    public HttpServer apply(final HttpServer httpServer) {
        return httpServer
                .tcpConfiguration(tcpServer -> tcpServer
                        .runOn(LoopResources.create("barrier-netty", 1, DEFAULT_IO_WORKER_COUNT*2, true), false)
                        .selectorOption(ChannelOption.SO_REUSEADDR, true)
                        .selectorOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                        .option(ChannelOption.TCP_NODELAY, true)
                        .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT));
    }
}
